package com.shipwe.loans.ui.fragment

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.shipwe.adapter.ShipweOnItemChildClickListener
import com.shipwe.loans.R
import com.shipwe.loans.databinding.FragmentMenuBinding
import com.shipwe.loans.pro.ShipweFragment
import com.shipwe.loans.ui.activity.ActivityAuthSteps
import com.shipwe.loans.ui.activity.ActivityLogin
import com.shipwe.loans.ui.activity.ActivityUserAdvise
import com.shipwe.loans.ui.activity.ActivitySetting
import com.shipwe.loans.ui.activity.ActivityUserInfo
import com.shipwe.loans.ui.activity.ActivityWebView
import com.shipwe.loans.ui.adapter.MenuItemAdapter
import com.shipwe.loans.ui.presenter.MenuPresenter
import com.shipwe.loans.ui.view.IMenuView
import com.shipwe.loans.utils.AppDensityUtil
import com.shipwe.loans.utils.AppLoadImageUtil
import com.shipwe.loans.utils.ShipweTitleBarUtil
import com.shipwe.loans.utils.event.AppEventData
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.utils.helper.CustomDataHelper
import com.shipwe.loans.utils.helper.CustomProcessHelper
import com.shipwe.loans.utils.helper.TestDataLibInvoke
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:49
 * @Annotation：侧边菜单
 */
class FragmentMenu(): ShipweFragment(), IMenuView, CoroutineScope by MainScope() {
    lateinit var binding: FragmentMenuBinding
    private var drawerLayout: DrawerLayout? = null
    var presenter: MenuPresenter? = null
    //菜单列表
    var menuAdapter: MenuItemAdapter? = null

    constructor(drawerLayout: DrawerLayout): this(){
        this.drawerLayout = drawerLayout
    }
    override fun getShipweRootView(inflater: LayoutInflater): View {
        binding = FragmentMenuBinding.inflate(inflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#00000000"))
        binding.menuContent.setPadding(AppDensityUtil.dp2px(14f), ShipweTitleBarUtil.getStatusBarHeight(), AppDensityUtil.dp2px(14f),0)
        initMenuListView()
    }

    override fun initShipweListener() {
        //关闭
        binding.menuClose.setOnClickListener {
            if (drawerLayout != null){
                drawerLayout!!.closeDrawer(GravityCompat.START)
            }
        }
        binding.menuUserInfo.setOnClickListener {
            binding.menuClose.callOnClick()
            launch(Dispatchers.Main){
                delay(300)
                onIntent(ActivityUserInfo::class.java)
            }
        }
        binding.menuPackUp.setOnClickListener {
            // TODO: 添加测试积分
//            UserPointsHelper.onSaveUserPointsAction("testAddPoints","Test Add Points","100000")
            if (drawerLayout != null){
                drawerLayout!!.closeDrawer(GravityCompat.START)
            }
        }
        binding.menuContent.setOnClickListener {
            return@setOnClickListener
        }
    }

    override fun initShipweData() {
        presenter = MenuPresenter(this)
        presenter!!.getMenuList()
        showMenuUserInfo()
    }

    /**
     * 初始化菜单列表
     */
    private fun initMenuListView() {
        binding.menuListView.layoutManager = LinearLayoutManager(getAct())
        menuAdapter = MenuItemAdapter(binding.menuListView)
        binding.menuListView.adapter = menuAdapter
        binding.menuListView.itemAnimator = DefaultItemAnimator()
        menuAdapter!!.setOnItemChildClickListener(ShipweOnItemChildClickListener { _, childView, position ->
            val item = menuAdapter!!.getItem(position)
            if (childView.id == R.id.menuItem) {//切换item
                when(item.optInt("menuId")){
                    0 -> {//Ask us
                        showCustomerDialog("User Center Page")
                        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,"User Center Page")
                    }
                    1 -> {//Information
                        showMenuAuthSteps()
                    }
                    2 -> {//Your advice
                        binding.menuClose.callOnClick()
                        launch(Dispatchers.Main){
                            delay(300)
                            onIntent(ActivityUserAdvise::class.java)
                        }
                    }
                    3 -> {//Privacy Policy
                        binding.menuClose.callOnClick()
                        launch(Dispatchers.Main){
                            delay(300)
                            val showTitle = getString(R.string.privacy_policy_title)
                            val linkUrl = CustomConfigsHelper.getShipwePrivacyPolicyLink()
                            ActivityWebView.start(requireContext(),showTitle, linkUrl)
                        }
                    }
                    4 -> {//setting
                        binding.menuClose.callOnClick()
                        launch(Dispatchers.Main){
                            delay(300)
                            onIntent(ActivitySetting::class.java)
                        }
                    }
                    else -> {//Log Out
                        onLoginOutClick()
                    }
                }
            }
        })
    }

    /**
     * 设置用户头像和昵称
     */
    private fun showMenuUserInfo(){
        val avatarUrl = CustomDataHelper.getShipweCustomUserAvatarUrl()
        if (avatarUrl.isNotEmpty()){
            AppLoadImageUtil.instance.loadImageUrl(requireContext(),binding.menuAvatar,avatarUrl)
        } else {
            binding.menuAvatar.setImageResource(R.drawable.load_holder)
        }
        binding.menuUserName.text = CustomDataHelper.getShipweCustomUserName()
    }

    override fun showMenuList(menuList: ArrayList<JSONObject>) {
        menuAdapter!!.data = menuList
    }

    /**
     * 跳转进件信息
     */
    private fun showMenuAuthSteps(){
        if (CustomProcessHelper.getAuthStepList().size == 0) {//流程已完成 - 提示
            showErrorTipsDialog(getString(R.string.menu_profile_complete_tips),"User Center Click Information")
        } else {
            //流程未完成 - 进入流程页面
            binding.menuClose.callOnClick()
            //上报
            TestDataLibInvoke.sycData()
            launch(Dispatchers.Main){
                delay(300)
                onIntent(ActivityAuthSteps::class.java)
            }
        }
    }

    /**
     * 退出登录
     */
    private fun onLoginOutClick(){
        appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_USER_LOGINOUT,"")
        //退出登录，需要移除用户保存的信息
        ShipweSharedHelper.onShipweUserLoginOut()

        launch(Dispatchers.Main){
            delay(300)
            onIntent(ActivityLogin::class.java)
        }
    }

    override fun onShipwePublishEvent(event: AppEventData) {
        when (event.eventType) {
            AppEventData.TYPE.SHIPWE_CUSTOM_DATA_REFRESHED -> {//自定义数据刷新完成
                //设置用户昵称和头像
                showMenuUserInfo()
            }
            else -> {
            }
        }
    }
}